﻿using System;
using System.IO;
using System.Net;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CI.Utility
{
    public static class CharacterPortraitStore
    {
        private static readonly DirectoryInfo StorePath = new DirectoryInfo("Cache/Portraits");

        static CharacterPortraitStore()
        {
            if (!StorePath.Exists) StorePath.Create();
        }

        public static ImageSource GetImageSourceForCharacter(int characterId)
        {
            FileInfo file = GetPortraitFile(characterId);

            if (file == null || !file.Exists) return null;

            return new BitmapImage(new Uri("file://" + file.FullName));
        }

        private static FileInfo GetPortraitFile(int characterId)
        {
            string s = characterId.ToString();

            if (s == "-5") s = "johnny5";

            return new FileInfo(Path.Combine(StorePath.FullName, s + ".jpg"));
        }

        public static ImageSource GetAndStoreImageForCharacter(int characterId)
        {
            var url = new Uri("http://img.eve.is/serv.asp?s=256&c=" + characterId);

            try
            {
                var request = WebRequest.Create(url) as HttpWebRequest;

                if (request == null) return null;

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (response == null) return null;

                    if (response.StatusCode != HttpStatusCode.OK) return null;

                    using (var stream = response.GetResponseStream())
                    {
                        File.WriteAllBytes(GetPortraitFile(characterId).FullName,StreamHelper.ReadByteArrayFromStream(stream,response.ContentLength));

                        return GetImageSourceForCharacter(characterId);
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}